#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Worker启动脚本
简化的Worker启动入口，提供命令行参数支持
"""

import sys
import os
import argparse
import logging
from pathlib import Path

try:
    # 尝试相对导入（当作为模块使用时）
    from .worker_client import WorkerClient
    from .config_manager import get_config
except ImportError:
    # 直接导入（当直接运行时）
    from worker_client import WorkerClient
    from config_manager import get_config


def setup_logging(log_level: str = "INFO", log_file: str = None):
    """设置日志配置"""
    # 转换日志级别
    numeric_level = getattr(logging, log_level.upper(), logging.INFO)

    # 日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

    # 配置根日志记录器
    root_logger = logging.getLogger()
    root_logger.setLevel(numeric_level)

    # 清除现有处理器
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)

    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)

    # 文件处理器（如果指定了日志文件）
    if log_file:
        try:
            # 确保日志目录存在
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)

            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setFormatter(formatter)
            root_logger.addHandler(file_handler)

            print(f"日志将保存到: {log_file}")
        except Exception as e:
            print(f"创建日志文件失败: {e}")


def check_prerequisites():
    """检查运行前提条件"""
    try:
        # 检查必要的依赖包
        required_packages = ['requests', 'psutil']
        missing_packages = []

        for package in required_packages:
            try:
                __import__(package)
            except ImportError:
                missing_packages.append(package)

        if missing_packages:
            print(f"缺少必要的依赖包: {', '.join(missing_packages)}")
            print("请运行以下命令安装:")
            print(f"pip install {' '.join(missing_packages)}")
            return False

        return True

    except Exception as e:
        print(f"检查前提条件异常: {e}")
        return False


def validate_config():
    """验证配置"""
    try:
        config = get_config()

        # 检查Worker是否启用
        if not config.is_worker_enabled():
            print("❌ Worker功能未启用")
            print("请在config.json中设置 worker.enabled 为 true")
            return False

        # 验证配置
        validation = config.validate_config()
        worker_valid = validation.get('worker', False)

        if not worker_valid:
            print("❌ Worker配置验证失败")
            print("请检查config.json中的worker配置项")
            return False

        # 显示配置信息
        worker_config = config.get_worker_config()
        print("✅ Worker配置验证通过")
        print(f"  Worker ID: {worker_config.get('id')}")
        print(f"  Worker名称: {worker_config.get('workerName')}")
        print(f"  调度系统: {worker_config.get('api_base')}")
        print(f"  最大并发: {worker_config.get('maxConcurrentTasks')}")

        return True

    except Exception as e:
        print(f"❌ 配置验证异常: {e}")
        return False


def show_status():
    """显示状态信息"""
    try:
        config = get_config()

        print("=" * 60)
        print("剪映草稿自动化 Worker 状态")
        print("=" * 60)

        # Worker配置状态
        if config.is_worker_enabled():
            worker_config = config.get_worker_config()
            print("Worker配置:")
            print(f"  状态: ✅ 已启用")
            print(f"  ID: {worker_config.get('id')}")
            print(f"  名称: {worker_config.get('workerName')}")
            print(f"  调度系统: {worker_config.get('api_base')}")
            print(f"  最大并发: {worker_config.get('maxConcurrentTasks')}")
            print(f"  支持能力: {', '.join(worker_config.get('capabilities', []))}")
        else:
            print("Worker配置: ❌ 未启用")

        # 其他配置状态
        print(f"\n输出路径: {config.get_output_path()}")

        oss_config = config.get_oss_config()
        if oss_config.get('enabled'):
            print(f"OSS上传: ✅ 已启用 ({oss_config.get('bucket_name', 'unknown')})")
        else:
            print("OSS上传: ❌ 未启用")

        print("=" * 60)

    except Exception as e:
        print(f"显示状态异常: {e}")


def create_sample_config():
    """创建示例配置文件"""
    try:
        config_path = "config.json"

        if os.path.exists(config_path):
            response = input(f"配置文件 {config_path} 已存在，是否覆盖? (y/N): ")
            if response.lower() != 'y':
                print("取消创建示例配置")
                return

        # 获取默认配置
        config = get_config()
        default_config = config.default_config

        # 启用Worker
        default_config['worker']['enabled'] = True

        # 保存配置
        import json
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(default_config, f, indent=2, ensure_ascii=False)

        print(f"✅ 示例配置文件已创建: {config_path}")
        print("请根据实际情况修改配置，特别是:")
        print("  - worker.id: 唯一的Worker标识")
        print("  - worker.workerName: Worker名称")
        print("  - worker.api_base: 调度系统API地址")
        print("  - worker.ipAddress: 本机IP地址")
        print("  - worker.hostname: 本机主机名")

    except Exception as e:
        print(f"创建示例配置失败: {e}")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description="剪映草稿自动化 Worker 客户端",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  python run_worker.py                    # 启动Worker
  python run_worker.py --status           # 显示状态
  python run_worker.py --create-config    # 创建示例配置
  python run_worker.py --log-level DEBUG  # 启用详细日志
  python run_worker.py --log-file worker.log  # 日志保存到文件
        """
    )

    parser.add_argument(
        '--status',
        action='store_true',
        help='显示Worker状态信息'
    )

    parser.add_argument(
        '--create-config',
        action='store_true',
        help='创建示例配置文件'
    )

    parser.add_argument(
        '--log-level',
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
        default='INFO',
        help='日志级别 (默认: INFO)'
    )

    parser.add_argument(
        '--log-file',
        type=str,
        help='日志文件路径'
    )

    parser.add_argument(
        '--config',
        type=str,
        default='config.json',
        help='配置文件路径 (默认: config.json)'
    )

    args = parser.parse_args()

    # 设置日志
    setup_logging(args.log_level, args.log_file)

    # 处理命令
    if args.create_config:
        create_sample_config()
        return 0

    if args.status:
        show_status()
        return 0

    # 检查运行前提条件
    print("检查运行环境...")
    if not check_prerequisites():
        return 1

    # 验证配置
    print("验证配置...")
    if not validate_config():
        print("\n配置验证失败，请检查配置文件或运行以下命令创建示例配置:")
        print("python run_worker.py --create-config")
        return 1

    # 启动Worker
    try:
        print("\n启动Worker客户端...")
        worker = WorkerClient()

        # 显示启动信息
        config = get_config()
        worker_config = config.get_worker_config()

        print("=" * 60)
        print("剪映草稿自动化 Worker 客户端")
        print("=" * 60)
        print(f"Worker ID: {worker_config.get('id')}")
        print(f"Worker名称: {worker_config.get('workerName')}")
        print(f"调度系统: {worker_config.get('api_base')}")
        print(f"最大并发任务: {worker_config.get('maxConcurrentTasks')}")
        print(f"支持能力: {', '.join(worker_config.get('capabilities', []))}")
        print(f"日志级别: {args.log_level}")
        if args.log_file:
            print(f"日志文件: {args.log_file}")
        print("=" * 60)
        print("按 Ctrl+C 停止Worker")
        print("=" * 60)

        # 运行Worker
        success = worker.run_forever()

        if success:
            print("\nWorker正常退出")
            return 0
        else:
            print("\nWorker启动失败")
            return 1

    except KeyboardInterrupt:
        print("\n\n收到中断信号，Worker正在停止...")
        return 0
    except Exception as e:
        print(f"\nWorker运行异常: {e}")
        return 1


if __name__ == "__main__":
    sys.exit(main())